using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Windows;
using ExamPaperEditingSystem.Services;
using ExamPaperEditingSystem.ViewModels;
using ExamPaperEditingSystem.Views;

namespace ExamPaperEditingSystem
{
    public partial class App : Application
    {
        private IHost? _host;

        protected override void OnStartup(StartupEventArgs e)
        {
            try
            {
                _host = Host.CreateDefaultBuilder()
                    .ConfigureServices((context, services) =>
                    {
                        // 注册服务
                        services.AddSingleton<IEmbeddingService, EmbeddingService>();
                        services.AddSingleton<IChatService, ChatService>();
                        services.AddSingleton<IVectorDatabaseService, VectorDatabaseService>();
                        services.AddSingleton<IKnowledgeGraphService, KnowledgeGraphService>();
                        services.AddSingleton<IDocumentProcessorService, DocumentProcessorService>();
                        services.AddSingleton<IExamPaperService, ExamPaperService>();
                        services.AddSingleton<IConfigurationService, ConfigurationService>();

                        // 注册ViewModels
                        services.AddTransient<MainWindowViewModel>();

                        // 注册Views
                        services.AddTransient<MainWindow>();
                    })
                    .Build();

                var mainWindow = _host.Services.GetRequiredService<MainWindow>();
                var viewModel = _host.Services.GetRequiredService<MainWindowViewModel>();
                mainWindow.DataContext = viewModel;
                mainWindow.Show();

                base.OnStartup(e);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show($"应用程序启动失败: {ex.Message}\n\n详细错误:\n{ex}", "启动错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Shutdown(1);
            }
        }

        protected override void OnExit(ExitEventArgs e)
        {
            _host?.Dispose();
            base.OnExit(e);
        }
    }
}